<template>
  <div>
    <div class="createimg-mokuai">
      <div class="createimg-index">
        <div class="createimg-name">
       <div class="createimg-name-font">
        
           新建相册
      </div> 
           <div class="createimg-index-select">
          <div class="createimg-left createimg-index-select-button"><el-button icon="el-icon-arrow-left" @click.native="returnButton" size="small">返回</el-button></div>
      </div>
        </div>
        <div class="createimg-content">
          <!-- 新建相册 -->
          <div class="createimg-setting">
            <el-form
              :model="ruleForm"
              status-icon
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm">
              <el-form-item label="*相册名称:" prop="imgname">
                <el-input v-model.number="ruleForm.imgname" maxLength=100></el-input>
              </el-form-item>
               <el-form-item label="相册封面:" prop="">
              <el-upload
                      class="upload-demo"
                      ref="upload"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :on-remove="handleRemove"
                      :file-list="fileList"
                      :before-upload="beforeAvatarUpload"
                      list-type="picture"
                      :http-request="modeUpload"
                         :on-success="handleAvatarSuccess"
                         :limit="1"
                         :on-change="handleChange">
                 <el-button  class="upload-width" size="small" type="primary" @click="submitUpload">点击上传</el-button>
                 <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
</el-upload>
              </el-form-item>
              <el-form-item label="相册描述：" prop="textarea">
                <el-input type="textarea" :rows="8" maxLength=500 placeholder="请输入内容" v-model="ruleForm.textarea"></el-input>
              </el-form-item>
              <el-form-item label="排序：" prop="sort">
                <el-input v-model.number="ruleForm.sort" maxLength=10></el-input>
              </el-form-item>
              <el-form-item class="commit-button">
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
/* 自定义 */
.createimg-left{
  
  float:left;
}
.createimg-mokuai {
  height: 800px;
  background-color: rgb(249, 249, 249);
  padding-top: 30px;
}
.createimg-index {
  width: 80%;
  margin: auto;
  background-color: rgb(255, 255, 255);
}
.createimg-name {
  width: 100%;
  height: 40px;
  background-color: rgb(240, 240, 240);
}
.createimg-name-font {
  height: 40px;
  line-height: 40px;
  margin-left: 20px;
  font-size: 14px;
  float: left;
}
.createimg-index-select{
  width:80px;
  float: right;
  margin-right: 20px;
  font-size: 14px;
  padding-top: 5px;

}
.createimg-index-select-button{
margin-right: 20px;
}
.createimg-content {
  width: 100%;
 padding-bottom: 10px;
}

.createimg-setting {
  margin-top: 20px;
  margin-left: 25%;
  width: 39%;
}
.upload-width{
  width: 250px;
   
}
.commit-button{
    
    margin-left: 80px;
}

</style>

<script>
import goodImgeListApi from "@/api/goods/imagelist";
export default {
  data() {
    // 表单
    var checkImgname = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("相册名称不能为空"))
      }
        callback();
      // setTimeout(() => {
      //   if (!Number.isInteger(value)) {
      //     callback(new Error("请输入相册名称"))
      //   } else {
      //     if (value < 11) {
      //       callback(new Error("有需求请设置本js"))
      //     } else {
      //       callback()
      //     }
      //   }
      // }, 1000)
    }
    var checkSort = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("排序不能为空"))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入序列,暂时是数字"))
        } else {
          // if (value < 11) {
          //   callback(new Error("目前版本太低，请设置js升级版本"))
          // } else {
            callback()
          // }
        }
      }, 1000)
    }

  
    return {
        requestUrl:goodImgeListApi.getRequestUrl().defaults.baseURL+"/api-goods/album/",
      
      // 表单
    //   上传图片
       fileList: [],
      ruleForm: {
           id:"",
        imgname: "",
        textarea:"",
        sort: ""

      },
        imageUrl: '',
        mode:"",
      rules: {
        imgname: [{ validator: checkImgname, trigger: "blur" }],
        sort: [{ validator: checkSort, trigger: "blur" }],
    
      }
    }
  },
  methods: {
 // 返回
         returnButton(){
             this.$router.replace({ path: "/goods/goodsImage" });
               
            },
      handleAvatarSuccess(res, file) {
          this.imageUrl = URL.createObjectURL(file.raw);
      },
      handleRemove(file, fileList) {
          console.log(file, fileList);
      },
      beforeAvatarUpload(file) {
          const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
          const isLt2M = file.size / 1024  < 500;

          if (!isJPG) {
              this.$message.error('封面只能是 JPG和png 格式!');
          }
          if (!isLt2M) {
              this.$message.error('封面大小不能超过 500kb!');
          }
          return isJPG && isLt2M;
      },
    // 表单
     handleChange(file, fileList) {
        // this.fileList = fileList.slice(-3);
      },
      submitUpload() {
          this.$refs.upload.submit();
      },
      modeUpload: function(item){
          this.mode = item.file;
      },
      initData: function (){

             if(this.$route.query.id != undefined){
                 this.ruleForm.imgname = this.$route.query.title;
                 this.ruleForm.id = this.$route.query.id;
                 this.ruleForm.sort = this.$route.query.sort;
                 this.ruleForm.textarea = this.$route.query.instruction;
                 this.fileList.push({name: "", url: this.$route.query.image});
             }

      },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
            let param = new FormData(); //创建form对象
            param.append('file',this.mode);
            param.append('id',this.$route.query.id);
            param.append('title',this.ruleForm.imgname);
            param.append('sort',this.ruleForm.sort);
            param.append('instruction',this.ruleForm.textarea);
            let config = {
                headers:{'Content-Type':'multipart/form-data'} //这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
            };
            this.axios.post(this.requestUrl+"form?token=11",param,config).then((response) => {
                if(response.data.code == 200){
                    this.$message({
                        type: 'success',
                        message: response.data.msg
                    });
                    this.$router.replace({path:"/goods/goodsImage"});
                }else{
                    this.$message({
                        type: 'error',
                        message: response.data.msg
                    });
                }
            })
        } else {
          return false
        }
      })
    }
  },
    mounted() {
        this.initData();
    }
}
</script>
